<?php
/**
 * Created by yuxianjun001@icloud.com.
 * User: wuchen
 * Date: 2019/4/2
 * Time: 11:18
 */

namespace App\Services\Order;


use App\Helpers\ItemHelper;
use App\model\BuyerInfoModel;
use App\model\OrderModel\BuyerOrderModel;
use App\Services\BaseService;
use Illuminate\Support\Facades\DB;

/**
 * 买家订单服务层
 * Class BuyerOrderService
 * @package App\Services\Order
 */
class BuyerOrderService extends BaseService
{
    protected $model;

    public function __construct()
    {
        $this->model = new BuyerOrderModel();
    }

    /**
     * 创建订单
     * @param Request $request
     */
    public function create($request)
    {
        try {
            $this->model->order_num    = ItemHelper::createItem('Buyer');//订单编号
            $this->model->order_source = $request->orderSource;//订单来源，1-app，2-小程序，3-其他
            $this->model->pay_way      = 0;//订单支付方式，0-未支付，1-支付宝，2-微信，3-其他，
            $this->model->status       = 1;//订单状态，1-待付款，2-等待商家接单，3-等待骑手接单，4-取货中，5-送货中，6-骑手确认到达，7-已评价，8-退款中，9-订单关闭

            $this->model->shipping_fee           = $request->shippingFee;//配送费
            $this->model->packing_fee            = $request->packingFee;//包装费
            $this->model->promotion_fee          = $request->promotionFee;//活动费
            $this->model->delivery_method        = $request->deliveryMethod ?: 1;//配送方式，默认1，1-骑手配送，2-自提
            $this->model->expected_delivery_time = $request->expectedDeliveryTime ?: 0;//期望送达时间，在用户下单后多久。0-表示立刻送达，一般为30分钟一个梯度，例如30，表示30分钟
            $this->model->shipping_address_id    = $request->shippingAddressId;

            //商家信息
            $this->model->business_id    = $request->businessId;//商家id，必填
            $this->model->business_name  = $request->businessName;//商家名称，非必填
            $this->model->business_phone = $request->businessPhone;//商家手机号

            //买家信息
            $this->model->buyer_id    = $request->buyerId;//用户id，必填
            $this->model->buyer_name  = $request->buyerName;//用户名称，非必填
            $this->model->buyer_phone = $request->buyerPhone;//用户名称，非必填

            //骑手信息
            $this->model->rider_id = $request->riderId;//用户名称，非必填

            $this->model->pay_way = 0;//支付方式，默认0-未支付

            $orderIntegral = 0;
            $totalAmount   = 0;
            if (!empty($request->goodsInfo)) {
                $goods = json_decode($request->goodsInfo);
                foreach ($goods as $v) {
                    $orderIntegral += $v->integral;
                    $totalAmount   += ($v->num * $v->sell_price);

                }
            }
            $this->model->goods_info     = $request->goodsInfo;//订单信息，一个json体，包含商品的信息，价格等需要冗余写入
            $this->model->order_integral = $orderIntegral;//订单可得积分，所有订单商品可得积分的和,（需要通过goods字段处理）
            $this->model->total_money    = $totalAmount;//订单总金额 （需要通过goods字段处理）

            $res = $this->model->save();

            if (!empty($res)) {
                return $this->response('', '订单创建成功');
            }
            return $this->response('', '订单创建失败', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '订单创建异常', 500);
        }

    }

    /**
     * 平台后端-订单列表
     * @param Request $request
     */
    public function listPlatForm($request)
    {
        try {
            $dbResult = DB::table('buyer_order')->where('deleted_at', null);
            if (!empty($request->orderNo)) {
                $dbResult = $dbResult->where('order_no', $request->orderNo);
            }
            if (!empty($request->status)) {
                $dbResult = $dbResult->where('status', $request->status);
            }
            if (!empty($request->buyerName)) {
                $dbResult = $dbResult->where('buyer_name', $request->buyerName);
            }

            if (!empty($request->buyerPhone)) {
                $dbResult = $dbResult->where('buyer_phone', $request->buyerPhone);
            }

            if (!empty($request->timeBegin) && !empty($request->timeEnd)) {
                $dbResult = $dbResult->whereBetween('created_at', [$request->timeBegin, $request->timeEnd]);
            }

            return $this->response($this->model->buildPaginate($dbResult, $request), '查询成功');
        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '查询异常', 500);
        }

    }

    /**
     * 平台后端-订单详情
     * @param Request $request
     */
    public function infoPlatForm($request)
    {
        $res = $this->model->where('id', $request->id)->first();
        if (empty($res)) {
            return $this->response('', '此订单不存在', 404);
        }
        return $this->response($res->toArray(), '查询成功');
    }

    /**
     * 平台后端-备注订单
     * @param Request $request
     */
    public function remarkPlatForm($request)
    {
        try {
            $res = $this->model->where('id', $request->id)->first();
            if (empty($res)) {
                return $this->response('', '此订货订单不存在', 404);
            }
            $data = [
                'remark' => $request->remark ?: '',
            ];
            $res  = $this->model->where('id', $request->id)->update($data);
            if (!empty($res)) {
                return $this->response('', '备注成功');
            }

            return $this->response('', '备注失败', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '备注异常', 500);
        }

    }

    /**
     * 平台后端-关闭订单
     * @param Request $request
     */
    public function closePlatForm($request)
    {
        try {
            $res = $this->model->where('id', $request->id)->first();
            if (empty($res)) {
                return $this->response('', '此订货订单不存在', 404);
            }
            $data = [
                'status' => 9,//订单状态，1-待付款，2-等待商家接单，3-等待骑手接单，4-取货中，5-送货中，6-骑手确认到达，7-已评价，8-退款中，9-订单关闭
            ];
            $res  = $this->model->where('id', $request->id)->update($data);
            if (!empty($res)) {
                return $this->response('', '订单关闭成功!');
            }

            return $this->response('', '订单关闭失败!', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '订单关闭异常', 500);
        }

    }

    /**
     * 平台后端-系统转单，系统转单应当涉及到新的派单通知，需要在通知系统实现后加入
     * @param Request $request
     */
    public function transferPlatForm($request)
    {
        try {
            $res = $this->model->where('id', $request->id)->first();
            if (empty($res)) {
                return $this->response('', '此订单不存在', 404);
            }
            $data = [
                'rider_id' => $request->rider_id,//订单状态，1-待付款，2-等待商家接单，3-等待骑手接单，4-取货中，5-送货中，6-骑手确认到达，7-已评价，8-退款中，9-订单关闭
            ];
            $res  = $this->model->where('id', $request->id)->update($data);
            if (!empty($res)) {
                return $this->response('', '系统转单成功!');
            }

            return $this->response('', '系统转单失败!', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '系统转单异常', 500);
        }

    }

    /**
     * 获取订单对应的用户收件地址
     * @param $request
     */
    public function buyerAddress($request)
    {
        try {
            $model = new BuyerInfoModel();
            $res   = $model->where(['id' => $request->id, 'deleted_at' => null])->first();
            if (empty($res)) {
                return $this->response('', '该用户收货地址信息不存在!', 404);
            }
            return $this->response($res->toArray(), '查询成功');

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '查询异常', 500);
        }
    }


}